package cn.shop.dys.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.markmao.pulltorefresh.widget.XListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.shop.dys.R;
import cn.shop.dys.adapter.LimitBuyItemAdapter;
import cn.shop.dys.adapter.LimitBuyItemAdapter2;
import cn.shop.dys.bean.ProductInfo;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.dys.constant.DBConstants;
import cn.shop.lib_common.CommonUtil;


/**
 * 限时抢购界面
 *
 * @author zhangun
 */
// http://localhost:8080/market/limitbuy?page=0&pageNum=10
    //TODO bug：倒计时在条目拖动时才走动，时间没走
public class LimitBuyActivity extends AppCompatActivity implements XListView.IXListViewListener {
    private static final String TAG = "LimitBuyActivity";
    @ViewInject(R.id.xlistview_limit_buy)
    XListView mXListView;
    @ViewInject(R.id.layout_empty)
    View layoutEmpty;
    @ViewInject(R.id.tv_title)
    TextView tvTitle;
    private List<ProductInfo> mProducts = new ArrayList<>();
    private LimitBuyItemAdapter2<ProductInfo> adapter;
    private HttpUtils mHttpUtils;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_limit_buy);
        ViewUtils.inject(this);
        tvTitle.setText("限时抢购");

        mHttpUtils = new HttpUtils();
        RequestParams requestParams = new RequestParams();
        requestParams.addQueryStringParameter("page", "0");
        requestParams.addQueryStringParameter("pageNum", "10");

        mHttpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.LIMITBUY_URL, requestParams, mCallBack);
        //mXListView数据填充，设置下拉刷新，上拉加载，条目监听属性
        setXListView();
        Log.d(TAG, "限时抢购：onCreate() ---");
//        setAdapter();//刷新适配器，填充数据到listView

    }

    private RequestCallBack<String> mCallBack = new RequestCallBack<String>() {
        @Override
        public void onSuccess(ResponseInfo<String> responseInfo) {
            String result = responseInfo.result;
            //Log.d(TAG, "第一次请求服务器json：" + result);
            try {
                parseJsonToList(result, mProducts);
                setAdapter();
                Log.d(TAG, "第一次请求服务器json集合长度 ：" + mProducts.size());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d(TAG, " 第一次请求服务器json集合：" + mProducts.toString());
        }

        @Override
        public void onFailure(HttpException e, String s) {
            Log.d(TAG, "限时抢购界面网络请求数据失败");
            e.printStackTrace();
        }
    };

    //解析json,添加到集合,
    private void parseJsonToList(String result, List<ProductInfo> list) throws JSONException {
        try {
            JSONObject obj = new JSONObject(result);
            String jsonProductList = obj.getString("productList");
            Gson gson = new Gson();
            ProductInfo[] productArray = gson.fromJson(jsonProductList, ProductInfo[].class);
            for (ProductInfo productInfo : productArray) {
                list.add(productInfo);
            }
            Log.d(TAG, "解析服务器json");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //设置XlistView刷新属性，
    private void setXListView() {
        mXListView.setEmptyView(layoutEmpty);
        mXListView.setPullRefreshEnable(true);
        mXListView.setPullLoadEnable(true);
        mXListView.setAutoLoadEnable(false);
        mXListView.setXListViewListener(this);
        String currentTime = CommonUtil.getCurrentTime();
        mXListView.setRefreshTime(currentTime);
    }

    private void setAdapter() {
        if (adapter == null) {
            Log.d(TAG, "setAdapter集合长度： " + mProducts.size());
            adapter = new LimitBuyItemAdapter2<>(this, mProducts);
            mXListView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }


    public void backPre(View view) {
        finish();
    }

    //请求更多新数据
    @Override
    public void onRefresh() {
        if (mProducts.size() < 10) {
            CommonUtil.showSafeToast(this, "已经是最新数据");
            mXListView.stopRefresh();
        } else {
            RequestParams requestParams = new RequestParams();
            requestParams.addQueryStringParameter("page", "0");
            requestParams.addQueryStringParameter("pageNum", "10");
            mHttpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.LIMITBUY_URL, requestParams, mRefreshCallBack);
        }
    }

    @Override
    public void onLoadMore() {
        if (mProducts.size() < 10) {
            CommonUtil.showSafeToast(this, "没有历史数据拉");
            mXListView.stopLoadMore();
        } else {
            RequestParams requestParams = new RequestParams();
            int morePage = 0;
            morePage += 10;
            requestParams.addQueryStringParameter("page", "" + morePage);
            requestParams.addQueryStringParameter("pageNum", "10");
            mHttpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.LIMITBUY_URL, requestParams, mLoadMoreCallBack);
        }
    }

    private RequestCallBack<String> mRefreshCallBack = new RequestCallBack<String>() {
        @Override
        public void onSuccess(ResponseInfo<String> responseInfo) {
            String result = responseInfo.result;
            List<ProductInfo> refreshCallBackList = new ArrayList<>();
            try {
                parseJsonToList(result, refreshCallBackList);
                mProducts.clear();
                mProducts.addAll(0, refreshCallBackList);
                setAdapter();
                mXListView.stopRefresh();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(HttpException e, String s) {
            mXListView.stopRefresh();
        }
    };

    //TODO 请求更多历史数据，
    private RequestCallBack<String> mLoadMoreCallBack = new RequestCallBack<String>() {
        @Override
        public void onSuccess(ResponseInfo<String> responseInfo) {
            String result = responseInfo.result;
            List<ProductInfo> loadMoreCallBackList = new ArrayList<>();
            try {
                parseJsonToList(result, loadMoreCallBackList);
                mProducts.addAll(loadMoreCallBackList);
                setAdapter();
                mXListView.stopLoadMore();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(HttpException e, String s) {
            mXListView.stopLoadMore();
        }
    };
}
